package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Resource
    AuthorMapper authorMapper;

    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    /**
     * 保存app文章
     *
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
//        1. 校验参数
        if (articleDto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
//        2. 封装文章ApArticle对象
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
//        3. 根据作者名称查询作者ID
        ApAuthor author = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getName, apArticle.getAuthorName()));
        if (author == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        apArticle.setAuthorName(author.getName());
//        4. 如果文章ID为null 添加文章
        if (apArticle.getId() == null) {
            // 普通文章
            apArticle.setComment(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            apArticle.setLikes(0);
            // 保存
            save(apArticle);  // 返回ID
        } else {
            //        5. 如果文章ID不为null 修改文章
            //        并删除之前配置 和 文章内容
            ApArticle article = getById(articleDto.getId());
            if (article == null) {
                log.info("文章信息为空 : {}", articleDto.getId());
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery()
                    .eq(ApArticleConfig::getArticleId, apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
            updateById(apArticle);
        }
        //添加文章配置
        //保存article_config 数据
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfigMapper.insert(apArticleConfig);
        //添加文章内容
        //保存文章article_content 数据
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setContent(articleDto.getContent());
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContentMapper.insert(apArticleContent);
        //返回文章ID
        return ResponseResult.okResult(apArticle.getId());
    }

    @Autowired
    ApArticleMapper apArticleMapper;
    @Value("${file.oss.web-site}")
    private String webSite;

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //检查参数
        if (dto.getSize() == null || dto.getSize() < 1 || dto.getSize() > 50) {
            dto.setSize(10);
        }
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult loadArtilceInfo(ArticleInfoDto dto) {
        //参数校验
        if (dto.getArticleId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "文章id不能为空");
        }
        //查询文章内容
        ApArticleContent content = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getArticleId()));
        if (content == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章信息不存在");
        }
        ApArticleConfig articleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, dto.getArticleId()));
        if (articleConfig == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章配置信息不存在");
        }
        if (articleConfig.getIsDown() || articleConfig.getIsDelete()) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已经下架");
        }
        Map map = new HashMap();
        map.put("content", content);
        map.put("config", articleConfig);
        return ResponseResult.okResult(map);
    }
}